package com.css.apps.task.exec;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.css.apps.task.job.JobManager;
import com.css.apps.task.model.TTask;
import com.css.db.query.QueryCache;

/**
 * CSS Task DoJob
 * 
 * @author WeidongWang
 * @since 2012-8-23
 * @version 0.1
 */
public class DoJob implements Job {
	private static Log log = LogFactory.getLog(DoJob.class);
	private static final SchedulerFactory sf;
	static {
		sf = new StdSchedulerFactory();
	}
	public void execute(JobExecutionContext context) {
		try {
			String jobName = context.getJobDetail().getKey().getName();
			JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
			TTask tt = (TTask) jobDataMap.get(jobName);
			if (tt != null) {
				if (tt.getOpenFlag() == null || !tt.getOpenFlag().equals("1")) {
					delTask(tt);
				} else
					JobManager.execute(tt);
			}
		} catch (Exception e) {
			log.error(e.getStackTrace());
		}
	}
	public void init() {
		try {
			@SuppressWarnings("unchecked")
			List<TTask> taskList = QueryCache.idToObj(TTask.class, new QueryCache(
					"select a.id from TTask a where a.openFlag=1").list());
			for (TTask tt : taskList)
				addTask(tt);
		} catch (Exception e) {
			log.error(e.getStackTrace());
		}
	}
	public void addTask(TTask tt) {
		try {
			if (tt == null || !tt.getOpenFlag().equals("1"))
				return;
			Scheduler sched = sf.getScheduler();
			// 定期执行new Dojob().execute()方法
			JobDetail job = newJob(DoJob.class).withIdentity("tName" + tt.getUuid(), "tGroup").build();
			job.getJobDataMap().put("tName" + tt.getUuid(), tt);
			CronTrigger trigger = newTrigger().withIdentity("tTrigger" + tt.getUuid(), "tGroup")
					.withSchedule(cronSchedule(tt.getExeCorn())).build();
			sched.scheduleJob(job, trigger);
			sched.start();
		} catch (Exception e) {
			log.error(e.getStackTrace());
		}
	}
	public void delTask(TTask tt) {
		try {
			Scheduler sched = sf.getScheduler();
			sched.deleteJob(new JobKey("tName" + tt.getUuid(), "tGroup"));
		} catch (Exception e) {
			log.error(e.getStackTrace());
		}
	}
	public void editTask(TTask tt) {
		delTask(tt);
		addTask(tt);
	}
	public static void main(String[] args) throws Exception {
		new DoJob().init();
	}
}
